// pages/test-jwt/test-jwt.js - JWT测试页面
Page({
  data: {
    testResult: '',
    tokenInfo: ''
  },

  onLoad() {
    this.testJWT();
  },

  testJWT() {
    try {
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      
      let result = '=== JWT测试结果 ===\n\n';
      
      result += '1. Token信息:\n';
      if (token) {
        result += `Token存在，长度: ${token.length}\n`;
        result += `Token前50字符: ${token.substring(0, 50)}...\n`;
        
        // 分析token结构
        const parts = token.split('.');
        result += `Token部分数量: ${parts.length}\n`;
        if (parts.length === 3) {
          result += `Header长度: ${parts[0].length}\n`;
          result += `Payload长度: ${parts[1].length}\n`;
          result += `Signature长度: ${parts[2].length}\n`;
        }
      } else {
        result += 'Token不存在\n';
      }
      
      result += '\n2. 用户信息:\n';
      if (userInfo) {
        result += `UserInfo存在: ${JSON.stringify(userInfo, null, 2)}\n`;
      } else {
        result += 'UserInfo不存在\n';
      }
      
      result += '\n3. 测试解析:\n';
      if (token) {
        try {
          // 手动解析JWT
          const parts = token.split('.');
          if (parts.length === 3) {
            const payload = parts[1];
            // 处理Base64 URL编码
            const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
            const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
            
            result += `原始payload: ${payload}\n`;
            result += `处理后base64: ${padded}\n`;
            
            // 尝试解码
            const decoded = this.base64Decode(padded);
            result += `解码结果: ${decoded}\n`;
            
            if (decoded) {
              const parsed = JSON.parse(decoded);
              result += `解析成功: ${JSON.stringify(parsed, null, 2)}\n`;
            }
          }
        } catch (error) {
          result += `解析失败: ${error.message}\n`;
        }
      }
      
      this.setData({ testResult: result });
      
    } catch (error) {
      this.setData({ 
        testResult: `测试过程出错: ${error.message}` 
      });
    }
  },

  // 简化的base64解码函数
  base64Decode(str) {
    try {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      let output = '';
      
      str = String(str).replace(/[=]+$/, ''); // 移除padding
      
      if (str.length % 4 === 1) {
        throw new Error('Invalid Base64 input length');
      }
      
      for (let bc = 0, bs = 0, buffer, i = 0; str.charAt(i) || (buffer = '=', i % 4); output += String.fromCharCode(255 & buffer >> (-2 * i & 6))) {
        buffer = chars.indexOf(str.charAt(i++));
        if (buffer === -1) {
          throw new Error('Invalid Base64 character');
        }
        buffer = bc % 4 ? buffer * 64 + bs : buffer;
        bs = bc++ % 4 ? bs : buffer;
      }
      
      return output;
    } catch (error) {
      return `Base64解码失败: ${error.message}`;
    }
  },

  copyResult() {
    wx.setClipboardData({
      data: this.data.testResult,
      success() {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  }
});
